
import Common from './common';

import {  base, toast, promptBox,output,print} from 'nc-lightapp-front';
import {hrAjax as ajax} from 'src/hrpub/common/utils/utils';
import _ from 'lodash';

export default class BatchAddAction extends Common {

    constructor(comp) {
        super();
        this.comp = comp;
    }

    historyState = null;

    // 给批量新增弹窗的查询弹窗添加查询信息
    addQueryConditionToMultiAddSearch = (template) => {

        const {props} = this.comp;
        const {exam} = props;

        template['multiadd'].items.forEach((item) => {
            if(item.attrcode === 'hi_psnjob.clerkcode') {
                item.queryCondition = {
                    pk_org: exam.refValue.refpk,
                    probationType:exam.probationType,
                    GridRefActionExt: 'nccloud.web.hryf.pub.sqlbuilder.BatchAddClerkcodeRefSqlBuilder',
                    optype: 2
                };
            }
        });
    }

    // 打开批量新增的查询台窗
    openBatchAddSearchModal = () => {
        const {props} = this.comp;
        const {search, meta} = props;
        let template = meta.getMeta();

        this.addQueryConditionToMultiAddSearch(template);

        search.openAdvSearch('multiadd', true);
    }

    // 打开批量新增弹窗
    openBatchModal = async () => {
        const {props} = this.comp;
        const {dispatch, exam } = props;
        try {
            // 新增前校验
            let postData = {
                pk_org: exam.refValue.refpk,
                probationType:exam.probationType === '3'?'':exam.probationType
            }
            let res = await dispatch({
                type: 'exam/batchAddChackBefore',
                payload: {
                    postData: postData
                }
            })
            if(res.success) {
                this.comp.props.dispatch({
                    type: 'exam/update',
                    payload: {
                        batchAddModalVisible: true
                    }
                });
            }
        }
        catch(e) {
            throw (e)
        }
    }

    // 关闭批量新增弹窗
    closeBatchModal = () => {
        this.comp.props.dispatch({
            type: 'exam/update',
            payload: {
                batchAddModalVisible: false,
                batchAddCurrentStep: 0
            }
        });
    }

    // 为了解决查询不能是async的问题
    toSearchWrapper = () => {
        this.toSearch();
    }

    // 批量新增弹窗第一步条件选择查询弹窗点击确认
    toSearch = async () => {

        const {props} = this.comp;
        const {dispatch, exam, editTable, search, meta} = props;

        let template = meta.getMeta();
        let postData = {
            ...search.getQueryInfo('multiadd',true),
            oid:template['multiadd'].oid,
            listpks: this.getExistPks(),
            pk_org: exam.refValue.refpk,
            probationType:exam.probationType === '3'?'':exam.probationType
        };

        try {
            let res = await dispatch({
                type: 'exam/batchAddSelPsnByConditionAction',
                payload: {
                    postData: postData
                }
            });
         
            if(res.success && res.data && res.data.list && res.data.list.list_batch) {
                editTable.setTableData('list_batch', res.data.list.list_batch);
            }

            if(res.data && res.data.warningMsg){
                toast({
                    color: 'warning',
                    content: res.data.warningMsg // 新增成功
                });
            }
        }
        catch(e) {
        }
    }

    // 获取已存在的listpks
    getExistPks = () => {
        const {props} = this.comp;
        const {dispatch, exam, editTable} = props;

        let tableData = editTable.getAllRows('list_batch');
        let listpks = tableData.map((item) => {
            return item.values['pk_psnjob'].value;
        });

        return listpks
    }

    // 批量新增弹窗第一步参照选择逻辑
    changePersonRefer = async (value) => {
        const {props} = this.comp;
        const {dispatch, exam, editTable} = props;
        let postData = {
            listpks: this.getExistPks(),
            pk_org: exam.refValue.refpk,
            refpks: ''
        };
  
        let refpks = value.map((item) => {
            return item.refpk;
        });
        postData['refpks'] = refpks;

        try {
            let res = await dispatch({
                type: 'exam/getBatchAddTableDataByRefer',
                payload: {
                    postData: postData
                }
            });

            if(res.success && res.data && res.data.list && res.data.list.list_batch) {
                editTable.setTableData('list_batch', res.data.list.list_batch);
            }

            if(res.data && res.data.warningMsg){
                toast({
                    color: 'warning',
                    content: res.data.warningMsg // 新增成功
                });
            }

            
        }
        catch(e) {
        }
    }

    // 获取并存储选择的行
    getSelectedRows = () => {
        const {props, state} = this.comp;
        const {exam, dispatch, editTable} = props;

        let selectedRows = [];

        // if(state.selectAll) {
        //     selectedRows = editTable.getAllRows('list_batch');
        // }
        // else {
            
            selectedRows = editTable.getCheckedRows('list_batch').map((item) => {
                return item.data
            });
        // }

        this.comp.setState({
            selectRows: selectedRows
        });

        return selectedRows;
    }

    // 批量添加弹窗点击下一步
    goToNextStep = () => {
        const {props} = this.comp;
        const {exam, dispatch, editTable, form, meta} = props;

        this.historyState = this.deepCopy(editTable.getAllRows('list_batch'));

        let selectRows = this.getSelectedRows();

        if(selectRows && selectRows.length <= 0) {
            this.toast({
                color: 'warning',
                content: exam.json['gx6008-000109'] //'请选择要转正的人员!'
            });
        }
        else {
            dispatch({
                type: 'exam/update',
                payload: {
                    batchAddCurrentStep: 1
                }
            });
             // 展开子列表
          

           
            let postData = {
                pk_org: exam.refValue.refpk,
                probationType:exam.probationType === '3'?'':exam.probationType
            }
            dispatch({
                type:'exam/batchAddNextStepAction',
                payload: {
                    postData:postData
                }
            })
            .then ((res) => {
                
                dispatch({
                    type: 'exam/update',
                    payload: {
                        type:res.data.formData.head.card_batch.rows[0].values.probation_type.value
                    }
                });

                let template = meta.getMeta();

                this.mergeTemplate(template, res.data.template);

                this.addonQueryCondition(template);
                console.log(template)
                meta.setMeta(template, () => {
                    form.openArea('card_batch', 'psninfo_batch');
                    form.openArea('card_batch', 'newinfo_batch');
                    form.openArea('card_batch', 'execinfo_batch');
                    form.openArea('card_batch', 'table_end_info_batch');
                    form.setAllFormValue({card_batch:res.data.formData.head.card_batch});
                    form.setFormStatus('card_batch', 'edit');
                });
            })

        }
    }

    // 合并新老模版
    mergeTemplate = (oldTemplate, newTemplate) => {
        for(let key in newTemplate){
            if(typeof newTemplate[key] === 'object') {
                Object.assign(oldTemplate[key], newTemplate[key]);
            }
        }
    }

    // 为每一个参照类型字段添加空的queryCondition对象
    addonQueryCondition = (template) => {
        for(let key in template){
            if(typeof template[key] === 'object' && template[key].items) {
                template[key].items.forEach((item) => {
                    if(item.itemtype === 'refer' && !item.queryCondition) {
                        item.queryCondition = {};
                    }
                });
            }
        }
    }

    // 批量添加弹窗点击上一步
    goToPrevStep = () => {
        const {props} = this.comp;
        const {exam, dispatch, editTable} = props;

        dispatch({
            type: 'exam/update',
            payload: {
                batchAddCurrentStep: 0
            }
        });

        if(this.historyState) {
            editTable.setTableData('list_batch', {rows: this.historyState}, false);
            this.historyState = null;
        }
    }

    // 当表格选择全部的时候
    selectedAll = (...args) => {
        this.comp.setState({
            selectAll: args[2]
        });
    }

    // 批量新增弹窗点击完成
    submitBatchAdd = async (postData) => {
        const {props, state} = this.comp;
        const {exam, dispatch, meta, form} = props;
        
        try {
            let res = await dispatch({
                type: 'exam/batchAddModalSubmit',
                payload: {
                    postData: postData
                }
            });

            if(res.success) {
                toast({
                    color: 'success',
                    content: exam.json['gx6008-000066'] // 新增成功
                });
                this.closeBatchModal();
                this.pubSub.publish('initData');
            }
        }
        catch(e) {
        }
    }


    batchAddChack = async () => {
        const {props, state} = this.comp;
        const {exam, dispatch, meta, form} = props;

        let postData = {
            listpks: '',
            formData: form.getAllFormValue('card_batch'),
            pk_org: exam.refValue.refpk,
            probationType:exam.probationType === '3'?'':exam.probationType
        };

        let listpks = state.selectRows.map((item) => {
            return item.values['pk_psnjob'].value
        });

        postData['listpks'] = listpks
        
        try {
            let res = await dispatch({
                type: 'exam/batchAddChack',
                payload: {
                    postData: postData
                }
            });

            if(res.success) {
                if(res.data&&res.data.tip===true){
                    toast({
                        color: 'info',
                        // light:true,
                        content: res.data.tipMsg // 新增成功
                    });
                }
                if(res.data&&res.data.warning===true){
                    toast({
                        color: 'warning',
                        content: res.data.warningMsg // 新增成功
                    });
                }
                this.submitBatchAdd(postData)
                
               
            }
        }
        catch(e) {
        }
    }
}